package programme

import (
	"fmt"
	"github.com/gocolly/colly"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gregex"
	"time"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/crawl/replayservice"
	"uni-crawl-frame/utils/timeutil"
)

type ProgrammeCrawl struct {
	*core.AbstractCrawlReplayUrl
}

func (receiver *ProgrammeCrawl) CreateProgram(replayConfig *entity.CmsCrawlReplayConfig, manifestTask *entity.CmsCrawlReplayManifestTask) {
	log := g.Log().Line()
	strs, _ := gregex.MatchString("(https://.*com)/(.*)", replayConfig.SeedUrl)
	//g.Dump(strs)
	//baseUrl := strs[1]
	channelName := strs[2]
	//var a ApiJson = new(ApiJson)

	log.Infof(gctx.GetInitCtx(), "获取节programme目单：%s", channelName)
	today := time.Now().Format(timeutil.YYYY_MM_DD_JOIN)
	var codeMap map[string]string = make(map[string]string)
	codeMap["jade"] = "J"
	codeMap["j2"] = "B"
	codeMap["tvb-news-channel"] = "C"
	codeMap["pearl"] = "P"
	codeMap["tvb-finance-sports-and-information-channel"] = "A"
	code := codeMap[channelName]
	coll := colly.NewCollector()
	var programs []programItem
	pLen := 0
	//index := 0
	url := fmt.Sprintf("https://programme.tvb.com/api/schedule?input_date=%s&network_code=%s", today, code)
	log.Infof(gctx.GetInitCtx(),
		"请求地址:%v", url)
	res := g.Client().GetContent(gctx.GetInitCtx(), url)
	var apiRes ApiJson
	//g.Dump(res)

	g.NewVar(res).Structs(&apiRes)
	proList := apiRes.Data.List[0].Schedules
	for j := 0; j < len(proList); j++ {
		programTask := new(entity.CmsCrawlReplayProgramTask)
		programTask.ManifestId = manifestTask.Id
		programTask.ConfigId = replayConfig.Id
		programTask.ProgramNo = g.NewVar(g.NewVar(proList[j].Event_datetime).GTime().Timestamp()).String()
		programTask.ProgramName = proList[j].Programme_title
		programTask.CrawlStatus = replayservice.ProgramTaskInit
		programTask.ProgramStartTime = g.NewVar(proList[j].Event_datetime).GTime()
		programTask.HostIp = replayConfig.Host
		//g.Dump(programTask)
		var endTime *gtime.Time
		if j == len(proList)-1 {
			endTime = gtime.New(proList[0].Event_datetime).Add(time.Hour * 24)
		} else {
			endTime = g.NewVar(proList[j+1].Event_datetime).GTime()
		}
		//sec := (programNextStarTime.TimestampMilli() - programTask.ProgramStartTime.TimestampMilli()) / 1000
		programTask.ProgramEndTime = endTime
		programTask.CreateTime = gtime.Now()

		replayservice.CheckAndSave(programTask)
	}

	coll.OnScraped(func(response *colly.Response) {
		log.Infof(gctx.GetInitCtx(),
			"电视台 = %s, 日期 = %s, 数量 = %d, 来源 = %s", channelName, today, pLen, url)
		if pLen == 0 {
			return
		}
		for i, program := range programs {

			var programNextStarTime *gtime.Time
			if i+1 == pLen {
				// 最后一个节目单无法计算时长，只能手动赋予一个
				programNextStarTime = gtime.NewFromTimeStamp(program.startTimestamp).Add(time.Hour)
			} else {
				// 下一个节目单的开始录制时间作为当前节目的结束录制时间
				programNextStarTime = gtime.NewFromTimeStamp(programs[i+1].startTimestamp)
			}

			programTask := new(entity.CmsCrawlReplayProgramTask)
			programTask.ManifestId = manifestTask.Id
			programTask.ConfigId = replayConfig.Id
			programTask.ProgramNo = program.startTimestampStr
			programTask.ProgramName = program.name
			programTask.CrawlStatus = replayservice.ProgramTaskInit
			programTask.ProgramStartTime = gtime.NewFromTimeStamp(program.startTimestamp)
			programTask.HostIp = replayConfig.Host
			sec := (programNextStarTime.TimestampMilli() - programTask.ProgramStartTime.TimestampMilli()) / 1000
			programTask.ProgramEndTime = programTask.ProgramStartTime.Add(gtime.S * time.Duration(sec))
			programTask.CreateTime = gtime.Now()

			replayservice.CheckAndSave(programTask)
		}
	})

	//_ = coll.Visit(url)

}

type programItem struct {
	startTimestampStr string
	startTimestamp    int64
	startTimeStr      string
	name              string
}
type ApiJson struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		Total int `json:"total"`
		List  []struct {
			Schedules []struct {
				Programme_title string `json:"programme_title"`
				Event_datetime  string `json:"event_datetime"`
			}
		} `json:"list"`
	} `json:"data"`
}
